package cn.eleven.dao.impl;


import cn.eleven.dao.UserDAO;
import cn.eleven.entity.User;
import cn.eleven.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户数据访问实现类
 */
public class UserDAOImpl implements UserDAO {

    /**
     * 根据用户名和密码查询用户信息
     */
    @Override
    public User findByUsernameAndPassword(Connection conn, String username, String password) throws SQLException {
        String sql = "SELECT id, username, password, role,room_occupied, user_Balance FROM user WHERE username = ? AND password = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setRole(rs.getString("role"));
                    user.setRoomOccupied(rs.getString("room_occupied"));
                    user.setUserBalance(rs.getDouble("user_Balance"));

                    return user;
                }
            }
        }
        return null;
    }

    /**
     * 根据用户ID查询用户信息
     */
    @Override
    public User findById(Connection conn, int userId) throws SQLException {
        String sql = "SELECT id, username, password, role, room_occupied, user_Balance FROM user WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setRole(rs.getString("role"));
                    user.setRoomOccupied(rs.getString("room_occupied"));
                    user.setUserBalance(rs.getDouble("user_Balance"));
                    return user;
                }
            }
        }
        return null;
    }

    /**
     * 更新用户的房间占用信息
     */
    @Override
    public boolean updateUserRoomOccupied(Connection conn, int userId, String roomName) throws SQLException {
        String sql = "UPDATE user SET room_occupied = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, roomName);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate() > 0;
        }
    }

    /**
     * 清除用户的房间占用信息
     */
    @Override
    public boolean clearUserRoomOccupied(Connection conn, int userId) throws SQLException {
        String sql = "UPDATE user SET room_occupied = NULL WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            return pstmt.executeUpdate() > 0;
        }
    }

    /**
     * 查询用户是否存在
     */
    public boolean isUserExists(String username) {
        String sql = "SELECT COUNT(*) FROM user WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    /**
     * 添加用户（注册）
     */
    public void addUser(User user) throws SQLException {
        String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.executeUpdate();
        }
    }

    /**
     * 通过用户名和密码查找用户
     */
    public User findUser(String username, String password) {
        String sql = "SELECT id, username FROM user WHERE username = ? AND password = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return new User(rs.getInt("id"), rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}